package com.usian.wemedia.gateway.filter;

import com.usian.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class MediaGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //交换机获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断当前请求是否为登录，如果是的话，直接放行
        if (request.getURI().getPath().contains("login/in")){
            return chain.filter(exchange);
        }
        //不是登录的情况，获取当前用户的请求头信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //判断当前令牌是否存在
        if (StringUtils.isBlank(token)){
            String json="{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        //获取令牌
        Claims claims = AppJwtUtil.getClaimsBody(token); //全局有效，耗时大
        int i = AppJwtUtil.verifyToken(claims);
        if (i==0 || i==-1){
            //获取令牌中的id
            Integer id = (Integer)claims.get("id");
            request.mutate().headers(httpHeaders -> {
                httpHeaders.set("userId",id.toString());
            }).build();
            //token快过期的情况，需要续签
            if (i==0){
                String newToken = AppJwtUtil.getToken(id.longValue());
                request.mutate().headers(httpHeaders -> {
                    httpHeaders.set("refresh_token",newToken);
                }).build();
            }
            exchange.mutate().request(request).build();
        }else {
            String json="{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
